#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define SERVER_PORT 55559       // 服务器端口
#define BUFFER_SIZE 1024       // 缓冲区大小

// 错误处理函数
void error(const char* msg) {
    perror(msg);
    exit(1);
}

// 主函数
int main() {
    int relay_socket, client_socket, server_socket;
    struct sockaddr_in relay_addr, client_addr, server_addr;
    socklen_t client_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];

    // 创建 socket
    relay_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (relay_socket < 0) error("ERROR opening relay socket");

    // 设置中继节点地址
    relay_addr.sin_family = AF_INET;
    relay_addr.sin_addr.s_addr = INADDR_ANY; // 监听所有接口
    relay_addr.sin_port = htons(55559);       // 中继端口

    // 绑定 socket
    if (bind(relay_socket, (struct sockaddr*)&relay_addr, sizeof(relay_addr)) < 0)
        error("ERROR on binding");

    // 开始监听
    listen(relay_socket, 5);
    printf("Relay node listening on port 55559...\n");

    // 设置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, "120.55.84.162", &server_addr.sin_addr); // 替换为实际服务器 IP

    while (1) {
        // 接受客户端连接
        client_socket = accept(relay_socket, (struct sockaddr*)&client_addr, &client_len);
        if (client_socket < 0) error("ERROR on accept");

        // 创建与服务器的 socket
        server_socket = socket(AF_INET, SOCK_STREAM, 0);
        if (server_socket < 0) error("ERROR opening server socket");

        // 连接到服务器
        if (connect(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
            error("ERROR connecting to server");
        }

        // 转发数据
        ssize_t n;
        while ((n = read(client_socket, buffer, sizeof(buffer))) > 0) {
            printf("客户端发送的数据大小:%ld\n", n);
            // 将数据发送到服务器
            write(server_socket, buffer, n);

            // 从服务器接收响应
            ssize_t m = read(server_socket, buffer, sizeof(buffer));
            printf("服务器响应的数据大小:%ld\n", m);

            if (m > 0) {
                // 将响应返回给客户端
                write(client_socket, buffer, m);
            }
        }

        // 关闭连接
        close(server_socket);
        close(client_socket);
    }

    // 关闭中继 socket
    close(relay_socket);
    return 0;
}

